package admin

import (
	"blogs/models"
	"blogs/utils"
	"github.com/beego/beego/v2/adapter"
	beego "github.com/beego/beego/v2/server/web"
)

// 关于对象的操作
type UserController struct {
	beego.Controller
}

// @Title Create
// @Description 添加轮播图
// @Param	body		body 	models.Focus	true		"The object content"
// @Success 200 {string} models.Object.Id
// @Failure 403 body is empty
// @router / [post]
func (o *UserController) Post() {

	title := o.GetString("Title")
	imgUrl := o.GetString("ImgUrl")
	link := o.GetString("Link")

	var ob models.Focus
	ob.Title = title
	ob.ImgUrl = imgUrl
	ob.Link = link
	ob.AddTime = int(utils.GetUnix())
	err := utils.DB.Create(&ob).Error
	if err != nil {
		o.Data["json"] = map[string]interface{}{
			"msg":  "创建错误",
			"data": "创建错误",
			"code": false,
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = map[string]interface{}{
		"msg":  "创建成功",
		"data": "创建成功",
		"code": true,
	}
	o.ServeJSON()

}

// @Title Delete
// @Description 删除轮播图
// @Param	ID		path 	string	true		"必传的id"
// @Success 200 {string} delete success!
// @Failure 403 ID必传参数
// @router /:id [delete]
func (o *UserController) Delete() {
	id := o.Ctx.Input.Param(":id")
	adapter.Info(id, ">>>>>>>>>><<<<<<<<<<")
	focus := models.Focus{}
	err := utils.DB.Where("id=?", id).Delete(&focus).Error
	if err != nil {
		o.Data["json"] = map[string]interface{}{
			"msg":  "删除错误",
			"data": "删除错误",
			"code": false,
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = map[string]interface{}{
		"msg":  "删除成功",
		"data": nil,
		"code": true,
	}
	o.ServeJSON()
}

// @Title Update
// @Description 更新轮播图
// @Success 200 {object} models.Focus
// @Failure 403 ID必传参数 其余参数按更新数据传入
// @router / [put]
func (o *UserController) Put() {
	id, _ := o.GetInt("Id")
	title := o.GetString("Title")
	imgUrl := o.GetString("ImgUrl")
	link := o.GetString("Link")

	var focus []models.Focus
	utils.DB.Where("id=?", id).Find(&focus)

	adapter.Info(focus, id, title, imgUrl, link, ">>>>>>>>>>>>>>>>")
	if len(focus) > 0 {
		focus[0].Title = title
		focus[0].ImgUrl = imgUrl
		focus[0].Link = link
		focus[0].AddTime = int(utils.GetUnix())
		utils.DB.Save(&focus)
		o.Data["json"] = map[string]interface{}{
			"msg":  "更新成功",
			"data": "更新成功",
			"code": true,
		}
		o.ServeJSON()
		return
	}

	o.Data["json"] = map[string]interface{}{
		"msg":  "更新错误",
		"data": "更新错误",
		"code": false,
	}
	o.ServeJSON()

}

// @Title Get
// @Description 轮播图列表
// @Success 200
// @router / [get]
func (o *UserController) Get() {
	focus := []models.Focus{}
	//utils.DB.Where("id in (?)", []int{1, 2, 3}).Find(&focus)
	utils.DB.Find(&focus)
	o.Data["json"] = focus
	o.ServeJSON()
}
